package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.ReceiveCodeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.model.ReceiveCode;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS11005Srvl
 */
public class CS11005Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
    private Database db; 
	private String vaUrlAddress;
	private String vaAgentBrowser;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11005Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	String vaProcessType = request.getParameter("process_type");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else{
			
			getDataTable(request,response);
		}
	
    	
    }
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vnCodeID = request.getParameter("id");
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		try {
			db.beginTransaction();
			voReceiveCodeDAO.deleteReseiveCodeByReceiveCode(vnSiteId, vnCodeID);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11005", JDate.getDate(), JDate.getTime(),vnUserId, "CS11005Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
		response.getWriter();
    }
    
    
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaCodeID = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		String vaTex = request.getParameter("tex");
		String vaOldCodeID = request.getParameter("oldCodeID");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		String vaCodeIDDupicate = voReceiveCodeDAO.findsReceiveCodeBySiteAndReceiveCode(vnSiteId, vaOldCodeID, vaCodeID);
		
		if(vaCodeIDDupicate == null){
			ReceiveCode receiveCode = new ReceiveCode();
			receiveCode.setVnSiteId(vnSiteId);
			receiveCode.setVnReceiveCode(vaCodeID);
			receiveCode.setVaDescription(vaDesp);
			receiveCode.setVaHaveVat(vaTex);
			receiveCode.setVnUpdateUserId(vnUserId);
			receiveCode.setVaUpdateDate(vaDate);
			receiveCode.setVaUpdateTime(vaTime);
			
			try {
				db.beginTransaction();
				voReceiveCodeDAO.upDateReceiveCode(vnSiteId, vaOldCodeID, receiveCode);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11005", JDate.getDate(), JDate.getTime(),vnUserId, "CS11005Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			} finally {
				db.close();
			}
			response.getWriter().write("success");;
			
		}else{
			response.getWriter().write("ReceiveCode_dupicate");
			
		}
		
		
    }
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaCodeID = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		String vaTex = request.getParameter("tex");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		ReceiveCodeDAO  daoReceiveCodeDAO = new ReceiveCodeDAO(db);
		String vaCodeIDDupicate = daoReceiveCodeDAO.findReceiveCodeBySiteAndReceiveCode(vnSiteId, vaCodeID);
		if(vaCodeIDDupicate == null){
			
			ReceiveCode voReceiveCode = new ReceiveCode();
			voReceiveCode.setVnSiteId(vnSiteId);
			voReceiveCode.setVnReceiveCode(vaCodeID);
			voReceiveCode.setVaDescription(vaDesp);
			voReceiveCode.setVaHaveVat(vaTex);
			voReceiveCode.setVnInsertUserId(vnUserId);
			voReceiveCode.setVaInsertDate(vaDate);
			voReceiveCode.setVaInsertTime(vaTime);
			
			try {
				db.beginTransaction();
				daoReceiveCodeDAO.addReceiveCode(voReceiveCode);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11005", JDate.getDate(), JDate.getTime(),vnUserId, "CS11005Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}finally{
				db.close();
			}
			response.getWriter().write("success");;
			
		}else{
			response.getWriter().write("ReceiveCode_dupicate");
			
		}
		
		
		
		
    }
    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		String vaCode = request.getParameter("id");
		this.db = new Database();
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("id", vaCode);
		jsonObject.put("desp", voReceiveCodeDAO.findFileBySiteAndReceiveCode(vnSiteId, vaCode , "DESCRIPTION"));
		jsonObject.put("HAVE_VAT" , voReceiveCodeDAO.findFileBySiteAndReceiveCode(vnSiteId, vaCode , "HAVE_VAT"));
		
		PrintWriter voOut = response.getWriter();
		
		db.close();
		voOut.print(jsonObject.toJSONString());
		//System.out.print(jsonObject.toJSONString());
    }
    
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
			
		this.db = new Database();
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		List<Map<String, Object>> voListFindAll;
		voListFindAll = voReceiveCodeDAO.findReceive_CodeBySite(vnSiteId);

		for (int i = 0; i < voListFindAll.size(); i++) {
			Map<String, Object> voMapItem = voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i + 1);
			voColumn.add(voMapItem.get("RECEIVE_CODE"));
			voColumn.add(voMapItem.get("DESCRIPTION"));
			voColumn.add(voMapItem.get("HAVE_VAT"));
			voRow.add(voColumn);
		}
	//	voObject.put("iTotalRecords", listFindAll.size());
		//voObject.put("iTotalDisplayRecords", listFindAll.size());
		
		voObject.put("aaData", voRow);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
	}

    		
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
